from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from lists.models import List, Item, ListMembership, PhotoItem
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.utils.simplejson import dumps, loads, JSONEncoder
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect

import os
import sys

def home(request):
    variables = RequestContext(request)
    if request.subdomain == "food":
        return render_to_response('lists/food.html', variables)
    return render_to_response('lists/main.html', variables)

def profile(request, username):
    user = get_object_or_404(User, username=username)
    variables = RequestContext(request, { "my_user" : user, "username" : username })
    if not request.user.is_authenticated():
        # show public view of profile
        return render_to_response('lists/public.html', variables)
    elif request.user.is_authenticated():
        if request.user.username != username:
            return render_to_response('lists/public.html', variables)
    return render_to_response('lists/profile.html', variables)

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            new_user = authenticate(username=new_user.username, password=form.cleaned_data["password1"])
            login(request, new_user)
            return HttpResponseRedirect("/" + new_user.username)
    else:
        form = UserCreationForm()
    variables = RequestContext(request, { "form": form })
    return render_to_response("registration/register.html", variables)

@csrf_exempt
def api_upload_list_photo(request, list_id):
    list = get_object_or_404(List, id=list_id)
    if request.method == 'POST':
        post = request.POST
        name, ext = os.path.splitext(post['name'])
        
        dest_path = "{upload_url}{ds}{file}{ext}". \
            format(upload_url=settings.IMAGE_UPLOAD_URL, ds=os.sep, file=name, ext=ext)
        
        print settings.IMAGE_UPLOAD_URL
        
        uploaded_file = request.FILES['file']
        chunk = request.REQUEST.get('chunk', '0')
        chunks = request.REQUEST.get('chunks', '0')
        
        #try:
        #    with open("/home/kliao/code/django/spindle" + dest_path, ('wb' if chunk == '0' else 'ab')) as f:
        #        for content in uploaded_file.chunks():
        #            f.write(content)
        #except Exception,e:
        #    print "hahahaa", e
         
        #file uploaded, save to db
        if int(chunk) + 1 >= int(chunks):
            try:
                p = PhotoItem(content_object=list)
                p.original_image.save(dest_path, uploaded_file, True)
            except Exception,e:
                print "sljfsakf", e
        
    return HttpResponse("ok", mimetype="text/plain")

def api_list_photos(request, list_id, photo_id):
    if request.method == 'GET':
        list = get_object_or_404(List, id=list_id)
        array_of_urls = [{"id": x.id, "thumb_url": x.thumbnail_image.url, "original_img_url": x.original_image.url} for x in list.photos.all()]
        json = dumps(array_of_urls, cls=JSONEncoder)
        return HttpResponse(json, mimetype='application/json')
    elif request.method == 'DELETE':
        photo = get_object_or_404(PhotoItem, id=photo_id)
        photo.delete();
        return HttpResponse("Ok")
    return HttpResponse("Ok")

def api_user_lists(request, username):
    the_user = User.objects.get(username=username)
    lists = List.objects.filter(user=the_user)
    array_of_dicts = [{"id": x.pk, "title": x.title, "ordering": x.ordering} for x in lists]
    json = dumps(array_of_dicts, cls=JSONEncoder)
    return HttpResponse(json, mimetype='application/json')
    

def api_list_items(request, list_id, item_id):
    print "api_list_items"
    if request.method == 'GET':
        print "get"
        lst = List.objects.get(id=list_id)
        array_of_dicts = [{"id": x.pk, "name": x.name, "content": x.content, "done": False} for x in lst.items.all()]
        json = dumps(array_of_dicts, cls=JSONEncoder)
        return HttpResponse(json, mimetype='application/json')
    elif request.method == 'POST':
        print "post"
        json = loads(request.raw_post_data)
        item = Item.objects.create(name=json['name'], content=json['content'])
        lst = List.objects.get(id=list_id)
        ListMembership.objects.create(item=item, list=lst)
        dict = {"id": item.pk, "name": item.name, "content": item.content, "done": json['done']}
        json = dumps(dict, cls=JSONEncoder)
        return HttpResponse(json, mimetype='application/json')
    elif request.method == 'PUT':
        print "put"
        json = loads(request.raw_post_data)
        item = Item.objects.get(id=item_id)
        item.name = json['name']
        item.content = json['content']
        item.save()
        dict = {"id": item.pk, "name": item.name, "content": item.content, "done": json['done']}
        print dict
        json = dumps(dict, cls=JSONEncoder)
        return HttpResponse(json, mimetype='application/json')
    elif request.method == 'DELETE':
        Item.objects.get(id=item_id).delete()
        lst = List.objects.get(id=list_id)
        lst.save()
    return HttpResponse("OK")
    
    
def api_list(request, id):
    print "api_list"
    if request.method == 'GET':
        lst = List.objects.get(id=id)
        dict = {"id": lst.pk, "title": lst.title, "ordering": lst.ordering}
        json = dumps(dict, cls=JSONEncoder)
        return HttpResponse(json, mimetype='application/json')
    elif request.method == 'POST':
        # maybe use django serializer here
        json = loads(request.raw_post_data)
        lst = List.objects.create(title=json['title'], user=request.user)
        dict = {"id": lst.pk, "title": lst.title}
        json = dumps(dict, cls=JSONEncoder)
        return HttpResponse(json, mimetype='application/json')      
    elif request.method == 'PUT':
        json = loads(request.raw_post_data)
        list = List.objects.get(id=id)
        list.title = json['title']
        print json['ordering']
        list.ordering = json['ordering']
        list.save()
    elif request.method == 'DELETE':
        list = List.objects.get(id=id)
        list.delete()
    return HttpResponse("OK")

def api_item(request, id):
    print "api_item"
    if request.method == 'GET':
        item = Item.objects.get(id=id)
        dict = {"id": item.pk, "name": item.name, "content": item.content, "done": False}
        json = dumps(dict, cls=JSONEncoder)
        return HttpResponse(json, mimetype='application/json')
    elif request.method == 'POST':
        # maybe use django serializer here
        json = loads(request.raw_post_data)
        Item.objects.create(name=json.name, content=json.content)
    elif request.method == 'PUT':
        json = loads(request.raw_post_data)
        item = Item.objects.get(id=json['id'])
        print item.name
    elif request.method == 'DELETE':
        pass
    return HttpResponse("OK")